﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace SerialDemo.AdditionalAttributes
{
    public static class SliderBehavior
    {
        public static readonly DependencyProperty IdProperty =
            DependencyProperty.RegisterAttached("Id",
                typeof(int),
                typeof(SliderBehavior));

        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.RegisterAttached("Command",
                typeof(ICommand),
                typeof(SliderBehavior),
                new PropertyMetadata(null, OnCommandChanged));


        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.RegisterAttached("CommandParameter",
                typeof(object),
                typeof(SliderBehavior),
                new PropertyMetadata(null));

        public static void SetId(DependencyObject obj,int value)
        {
            obj.SetValue(IdProperty, value);
        }

        public static int GetId(DependencyObject obj)
        {
            return (int)obj.GetValue(IdProperty);
        }


        public static ICommand GetCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(DependencyObject obj,ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        public static object GetCommandParameter(DependencyObject obj)
        {
            return obj.GetValue(CommandParameterProperty);
        }

        public static void SetCommandParameter(DependencyObject obj, object value)
        {
            obj.SetValue(CommandParameterProperty, value);
        }


        private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
           if(d is Slider slider)
            {
                if (e.OldValue != null)
                    slider.ValueChanged -= OnValueChanged;
                if (e.NewValue != null)
                    slider.ValueChanged += OnValueChanged;
            }
        }

        private static void OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            var slider = sender as Slider;
            var command = GetCommand(slider);
            var commandParameter = GetCommandParameter(slider);
            object parameter = commandParameter ?? e.NewValue;
            if (command != null && command.CanExecute(e.NewValue))
                command.Execute(parameter);
            else
            {
                MessageBox.Show("Command is null or CanExecute returned false");
            }
        }
    }
}
